import axios from 'axios'

const api = axios.create({
    baseURL: 'http://127.0.0.1:8000',
    headers: {
        'Content-Type': 'application/json'
    }
})

export default function useApi() {
    const addConversation = async (userId) => {
        try {
            const response = await api.post('/home/q1/', {
                user: userId
            })
            return response.data.data
        } catch (error) {
            console.error('添加会话失败:', error)
            throw error
        }
    }

    const getAnswer = async (qaId, question) => {
        try {
            const response = await api.post('/home/q2/', {
                qa: qaId,
                question: question
            })
            return response.data.data
        } catch (error) {
            console.error('获取回答失败:', error)
            throw error
        }
    }

    const updateConversationName = async (id, question) => {
        try {
            const response = await api.post('/home/q3/', {
                id: id,
                question: question
            })
            return response.data.data
        } catch (error) {
            console.error('更新会话名称失败:', error)
            throw error
        }
    }

    const getAllConversations = async (userId) => {
        try {
            const response = await api.get('/home/q4/', {
                params: {user: userId}
            })
            return Array.isArray(response.data?.data) ? response.data.data : []
        } catch (error) {
            console.error('获取会话列表失败:', error)
            return []
        }
    }

    const getConversationDetails = async (id) => {
        try {
            const response = await api.get('/home/q5/', {
                params: {id: id}
            })
            return Array.isArray(response.data?.data) ? response.data.data : []
        } catch (error) {
            console.error('获取会话详情失败:', error)
            return []
        }
    }

    // 单轮问答接口
    const singleQA = async (question) => {
        try {
            const response = await api.post('/qa/qa1/', { question })
            const { code, message, data } = response.data || {}
            if (code === 1) {
                return data
            }
            throw new Error(message || '请求失败')
        } catch (error) {
            console.error('单轮问答失败:', error)
            throw error
        }
    }

    return {
        addConversation,
        getAnswer,
        updateConversationName,
        getAllConversations,
        getConversationDetails,
        singleQA
    }
}